<template>
  <div>
    <Button type="primary" class="back-button" @click="back()" icon="md-arrow-back">返回赛事列表</Button>
    <Card class="search-condition m-b-sm">
      <Row v-if="detail.eventsName" class="detail">
        <span>{{$config.userName(detail.eventsName,detail.eventsEnglishName)}}：</span>
        <Button @click="see" style="border: none;color: #359AFF;">查看基本信息</Button>
      </Row>
      <Row>
        <span>单场比赛名称：</span>
        <Input v-model="pageModel.fieldName" placeholder="请输入" clearable style="width: 150px" />
        <span>比赛阶段：</span>
        <InputNumber v-model="pageModel.fieldstartNumber" placeholder="请输入" clearable style="width: 100px" /><span style="margin:0;padding:0 10px">一</span>
        <InputNumber v-model="pageModel.fieldendNumber" placeholder="请输入" clearable style="width: 100px" />
        <span>比赛时间：</span>
        <DatePicker type="date" placeholder="请选择" style="width: 120px;margin-right:10px" v-model="pageModel.fieldstartTime"></DatePicker>
        <DatePicker type="date" placeholder="请选择" style="width: 120px;margin-right:10px" v-model="pageModel.fieldendTime"></DatePicker>
        <Button @click="fetchListStart" class="m-l-sm" type="primary" icon="md-search">筛选</Button>
        <Button @click="reset" class="m-l-sm" icon="md-sync">重置</Button>
      </Row>
    </Card>
    <Row class=" m-t-sm" v-if='(access.includes("GAME_MANAGER")&&!["1"].includes(checkObj.verifyStatus))||(access.includes("GAME_MANAGE")&&!["0","1"].includes(checkObj.verifyStatus))'>
      <Button type="primary" @click="dialog()" icon="md-add">添加比赛场次</Button>
      <Poptip v-if="access.includes('GAME_MANAGE')" title="您确定要删除选中数据吗?" :confirm="true" :transfer="true" @on-ok="delMore()"><Button type="error">批量删除</Button></Poptip>
      <Button type="primary" :disabled="!selectedTableItems.length||detail.competitionState === '1'||access.includes('GAME_MANAGER')" @click="public(null, '0')">发布</Button>
      <Button type="primary" :disabled="!selectedTableItems.length||detail.competitionState === '1'||access.includes('GAME_MANAGER')" @click="public(null, '1')">取消发布</Button>
      <Button type="primary" @click="downloadExcel">导入模板下载</Button>
      <upload-excel-button @upload="importExcel" type='primary' text="批量导入"></upload-excel-button>
      <Button type="primary" @click="exportExcel">导出Excel</Button>

    </Row>
    <div v-if="initing">
      <Card>
        <Row>
          <Table :loading="loading" stripe border ref="selection" @on-selection-change="isSelected" :columns="tableColumns" :data="tableData"></Table>
          <page-temp :total="total" :current="page.pageNo" :size="page.pageSize" @changePage='changePage'></page-temp>
        </Row>
      </Card>
      <Modal :styles="{top: '0px'}" v-model="visible" width='800' :mask-closable="false" :closable="false" title="编辑">
        <Card>
          <Row>
            <Col span="14" offset="5">
            <Form ref="model" :model="model" :rules="ruleInline" inline :label-width="100">
              <Row>
                <Col>
                <FormItem prop="fieldNumber" style="width:100%;" label="比赛场次">
                  <Input v-model="model.fieldNumber" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldName" style="width:100%;" label="单场比赛名称">
                  <Input v-model="model.fieldName" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldEnglishName" style="width:100%;" label="单场比赛名称（English）">
                  <Input v-model="model.fieldEnglishName" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <!-- <Row>
                <Col>
                <FormItem prop="qualifyingMatch" style="width:100%;" label="是否资格赛">
                  <i-switch v-model="model.qualifyingMatch" :value="model.qualifyingMatch" size="large" :true-value='1' :false-value='0'>
                    <span slot="open">是</span>
                    <span slot="close">否</span>
                  </i-switch>
                </FormItem>
                </Col>
              </Row> -->
              <Row v-if="detail.kindCode != 20">
                <Col>
                <FormItem prop="gradeCode" style="width:100%;" label="比赛级别">
                  <dict code="ZGX_BSJB" model="model.gradeCode" :parentCode='detail.kindCode' :value="model.gradeCode" @click="getVal" style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="eventsType" style="width:100%;" label="比赛类型">
                  <dict code="ZGX_BSLX" model="model.eventsType" :value="model.eventsType" @click="getVal" style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col v-if="['-1','0'].includes(this.detail.kindCode)">
                <FormItem style="width:100%;" label="单场比赛日期">
                  <DatePicker type="date" :options="opFieldTime" placeholder="请选择" style="width:100%;" v-model="model.fieldTime"></DatePicker>
                </FormItem>
                </Col>
                <Col v-else>
                <FormItem prop="fieldTime" style="width:100%;" label="单场比赛日期">
                  <DatePicker type="date" :options="opFieldTime" placeholder="请选择" style="width:100%;" v-model="model.fieldTime"></DatePicker>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col v-if="['-1','0'].includes(this.detail.kindCode)">
                <FormItem style="width:100%;" label="比赛结束日期">
                  <DatePicker type="date" :options="opFieldTime2" placeholder="请选择" style="width:100%;" v-model="model.fieldEndTime"></DatePicker>
                </FormItem>
                </Col>
                <Col v-else>
                <FormItem prop="fieldEndTime" style="width:100%;" label="比赛结束日期">
                  <DatePicker type="date" :options="opFieldTime2" placeholder="请选择" style="width:100%;" v-model="model.fieldEndTime"></DatePicker>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="operatingCompany" style="width:100%;" label="承办单位">
                  <Select v-model="model.operatingCompany" placeholder="请选择" clearable style="width: 100%;">
                    <Option v-for="(_item,index) in units" :key="index" :value="_item.teamId">{{_item.teamName}}</Option>
                  </Select>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldAddressCountry" style="width:100%;" label="比赛地点-国家">
                  <dict model="model.fieldAddressCountry" :value="model.fieldAddressCountry" @getCode="getCode" @click="getVal" code="AG_OUT" style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-省份" prop="fieldAddressProvince" style="width:100%;">
                  <dict model="model.fieldAddressProvince" :value="model.fieldAddressProvince" @getCode="getCode" @click="getVal" code="AG_IN" style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-地市" prop="fieldAddressCity" style="width:100%;">
                  <dict model="model.fieldAddressCity" :value="model.fieldAddressCity" @click="getVal" @getCode="getCode" code="AG_IN" :parentCode='model.fieldAddressProvince' style="width:100%;"></dict>
                </FormItem>
                <FormItem v-if="model.fieldAddressCountry==='A156'" label="比赛地点-区县" prop="fieldAddressCounty" style="width:100%;">
                  <dict model="model.fieldAddressCounty" :value="model.fieldAddressCounty" @click="getVal" code="AG_IN" :parentCode='model.fieldAddressCity' style="width:100%;"></dict>
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col v-if="model.fieldAddressCountry!=='A156'">
                <FormItem prop="address" style="width:100%;" label="比赛地点">
                  <Input v-model="model.address" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
              <Row>
                <Col>
                <FormItem prop="fieldCourt" style="width:100%;" label="比赛球场">
                  <Input v-model="model.fieldCourt" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
               <Row>
                <Col>
                <FormItem prop="fieldCourt" style="width:100%;" label="奖金">
                  <Input v-model="model.bonus" placeholder="请输入" />
                </FormItem>
                </Col>
              </Row>
            </Form>

            </Col>
          </Row>
          <!-- <spin-temp v-if="loading"></spin-temp> -->
        </Card>
        <div slot="footer">
          <Button @click="cancel">取消</Button>
          <Button @click="save" class="m-l-md" type="primary">确认</Button>
        </div>
      </Modal>
    </div>

  </div>
</template>

<script>
import dict from '_c/dict/dict.vue';
import dictSpan from '_c/dict/dict-span.vue';
import { getDict, check } from '@/api/configure';
import Api from '@/api/game';
import ApiApply from '@/api/game-apply';
import uploadExcelButton from '_c/upload/upload-excel-button.vue';
const api = new Api();
const apiApply = new ApiApply();
// 赛事管理
export default {
  props: ['kindCode'],
  components: {
    dict,
    dictSpan,
    uploadExcelButton
  },
  data() {
    return {
      initing: false,
      loading: true,
      saving: false,
      total: 0,
      visible: false,
      delModal: false,
      access: this.$store.state.user.access,
      AGOUTS: [],
      AGINS: [],
      units: [],
      detail: {
        eventsId: this.$route.params.id
      },
      // 发布 取消发布
      selectedTableItems: [],
      pageModel: {
        fieldName: null,
        fieldTime: null,
        fieldstartNumber: null,
        fieldendNumber: null,
        fieldstartTime: null,
        fieldendTime: null
      },
      opFieldTime: {
        disabledDate: date => {
          let self = this;
          // console.log(11111,date,date.valueOf(),self.detail.startTime,self.detail.endTime)
          // debugger
          // return (
          //   date &&
          //   !(
          //     date.valueOf() >= self.detail.startTime &&
          //     date.valueOf() <= self.detail.endTime
          //   )
          // );
          return (
            date &&
            !(
              date.valueOf() <= self.detail.endTime
            )
          );
        }
      },
      opFieldTime2: {
        disabledDate: date => {
          let self = this;
          return (
            date &&
            self.model.fieldTime &&
            !(
              date.valueOf() >= self.model.fieldTime &&
              date.valueOf() <= self.detail.endTime
            )
          );
        }
      },
      checkObj: { verifyStatus: null },
      model: {
        eventsId: this.$route.params.id,
        gradeCode: null,
        fieldNumber: null,
        fieldName: null,
        fieldEnglishName: null,
        eventsType: null,
        fieldTime: null,
        fieldEndTime: null,
        address: null,
        fieldCourt: null,
        fieldAddressCountry: null,
        fieldAddressProvince: null,
        fieldAddressCity: null,
        fieldAddressCounty: null,
        operatingCompany: null,
        kindCode: null
      },
      modelTemp: {
        eventsId: this.$route.params.id,
        // qualifyingMatch: 0,
        gradeCode: null,
        fieldNumber: null,
        fieldName: null,
        fieldEnglishName: null,
        eventsType: null,
        fieldTime: null,
        fieldEndTime: null,
        address: null,
        fieldCourt: null,
        fieldAddressCountry: 'A156',
        fieldAddressProvince: null,
        fieldAddressCity: null,
        fieldAddressCounty: null,
        operatingCompany: null,
        kindCode: null
      },
      page: {
        eventsId: this.$route.params.id,
        pageSize: this.$config.PAGE_SIZE,
        pageNo: 1
      },
      // 表单验证
      ruleInline: {
        fieldNumber: [
          { required: true, message: '请输入' },
          {
            pattern: this.$config.numReg,
            message: '请输入数字'
          },
          {
            max: this.$config.INPUT_NUMBER_SIZE,
            message: `数字最长为${this.$config.INPUT_NUMBER_SIZE}位`,
            transform(value) {
              return value == null ? '' : value.toString();
            }
          }
        ],
        fieldName: [
          { required: true, message: '请输入' },
          {
            max: this.$config.INPUT_ENGLISH_SIZE,
            message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`
          }
        ],
        fieldEnglishName: [
          {
            max: this.$config.INPUT_ENGLISH_SIZE,
            message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`
          }
        ],
        // gradeCode: [{ required: true, message: '请选择' }],
        eventsType: [{ required: true, message: '请选择' }],
        fieldTime: [
          {
            required: true,
            type: 'date',
            message: '请选择',
            trigger: 'change'
          }
        ],
        fieldEndTime: [
          {
            required: true,
            type: 'date',
            message: '请选择',
            trigger: 'change'
          }
        ],
        operatingCompany: [{ required: false, message: '请选择' }],
        // 国家
        fieldAddressCountry: [{ required: false, message: '请选择' }],
        // 省份
        fieldAddressProvince: [{ required: false, message: '请选择' }],
        // 地市
        fieldAddressCity: [{ required: false, message: '请选择' }],
        // 县区
        fieldAddressCounty: [{ required: false, message: '请选择' }],
        address: [{ required: false, message: '请输入' }],
        fieldCourt: [
          // { required: true, message: "请输入" },
          {
            max: this.$config.INPUT_SIZE,
            message: `最多输入${this.$config.INPUT_SIZE}个字符`
          }
        ]
      },
      tableColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '比赛阶段',
          key: 'fieldNumber',
          width: 100,
          align: 'left',
          render: (h, params) => {
            let self = this;
            return h(
              'span',
              self.$config.fieldNumberStr(params.row.fieldNumber)
            );
          }
        },
        {
          title: '单场比赛名称',
          key: 'fieldName',
          align: 'left',
          render: (h, params) => {
            let self = this;
            let title = self.$config.userName(
              params.row.fieldName,
              params.row.fieldEnglishName
            );
            return h('span', { domProps: { title } }, title);
          }
        },
        {
          title: '比赛级别',
          key: 'gradeCode',
          align: 'left',
          width: 100,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: 'ZGX_BSJB',
                parentCode: this.detail.kindCode,
                value: params.row.gradeCode
              }
            });
          }
        },
        {
          title: '比赛类型',
          key: 'eventsType',
          align: 'left',
          width: 100,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: 'ZGX_BSLX',
                value: params.row.eventsType
              }
            });
          }
        },
        {
          title: '比赛日期',
          key: 'fieldTime',
          align: 'left',
          // ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = ''
            if(['-1','0'].includes(this.detail.kindCode)) {
              title = self.$config.getUndetermined(
                params.row.fieldTime,
                params.row.fieldEndTime
              );
            } else {
              title = self.$config.getDate(
                params.row.fieldTime,
                params.row.fieldEndTime
              );
            }
            return h('span', { domProps: { title } }, title);
          }
        },
        {
          title: '比赛地点',
          key: 'fieldAddressCountry',
          align: 'left',
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.fieldAddress(
              params.row,
              self.AGOUTS,
              self.AGINS
            );
            return h('span', { domProps: { title } }, title);
          }
        },
        {
          title: '比赛球场名称',
          key: 'fieldCourt',
          align: 'left',
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = params.row.fieldCourt;
            return h('span', { domProps: { title } }, title);
          }
        },
        // {
        //   title: "承办单位",
        //   key: "operatingCompany",
        //   align: "left",
        //   ellipsis: true,
        //   render: (h, params) => {
        //     let self = this;
        //     let row = self.units.find(
        //       x => x.teamId === params.row.operatingCompany
        //     ) || { teamName: params.row.operatingCompany };
        //     let title = row.teamName;
        //     return h("span", { domProps: { title } }, title);
        //   }
        // },
        {
          title: '发布状态',
          key: 'state',
          align: 'left',
          width: 85,
          render: (h, params) => {
            return h(dictSpan, {
              style: { color: params.row.state === '0' ? 'green' : '#CCCCCC' },
              props: { code: 'ZGX_BSFB', value: params.row.state }
            });
          }
        },
        {
          title: '奖金',
          key: 'bonus',
          align: 'left',
          render: (h, params) => {
            let self = this;
            let title = self.$config.priceWithTag(
              params.row.bonus,
            );
            return h('span', { domProps: { title } }, title);
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'left',
          width: 200,
          render: (h, params) => {
            let self = this;
            if (['0', '1'].includes(self.checkObj.verifyStatus)) {
              return h('span');
            }
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      self.dialog(params.row);
                    }
                  }
                },
                '修改'
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除这条数据吗?',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      //删除数据
                      this.del(params.row.fieldId);
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        marginRight: '5px'
                      },
                      props: {
                        size: 'small',
                        type: 'error',
                        placement: 'top'
                      }
                    },
                    '删除'
                  )
                ]
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled:
                      self.detail.competitionState === '1' ||
                      self.access.includes('GAME_MANAGER')
                  },
                  on: {
                    click: () => {
                      this.public(
                        params.row.fieldId,
                        Math.abs(params.row.state - 1)
                      );
                    }
                  }
                },
                params.row.state === '1' ? '发布' : '取消发布'
              )
            ]);
          }
        }
      ],
      tableData: []
    };
  },
  watch: {
    'model.fieldTime': function(newVal) {
      let self = this;
      if (
        newVal != null &&
        // || newVal.valueOf() < self.detail.startTime
        (newVal.valueOf() > self.detail.endTime)
      ) {
        self.model.fieldTime = null;
      }
      if (
        self.model.fieldTime != null &&
        self.model.fieldEndTime != null &&
        self.model.fieldTime.valueOf() > self.model.fieldEndTime.valueOf()
      ) {
        self.model.fieldEndTime = null;
      }
    },
    'model.fieldEndTime': function(newVal) {
      let self = this;
      if (
        newVal != null &&
        self.model.fieldTime != null &&
        (newVal.valueOf() > self.detail.endTime ||
          newVal.valueOf() < self.model.fieldTime)
      ) {
        self.model.fieldEndTime = null;
      }
    },
    'detail': function(newVal) {
      if(newVal.kindCode == 20) {
         this.tableColumns = this.tableColumns.filter(
          x => !["gradeCode"].includes(x.key)
        );
      }
    }
  },
  created() {
    // if (self.access.includes("GAME_MANAGER")) {
    if (this.$route.params.id) {
      check(this.$route.params.id).then(data => {
        this.checkObj = data;
        let str = null;
        switch (data.verifyStatus) {
          case '0':
            str = '赛事公司正在处理这条赛事，请稍后处理';
            break;
          case '1':
            str = '赛事公司已对这个赛事发起申请，请前往审核当前赛事';
            break;
        }
        if (str != null) {
          if (this.access.includes('GAME_MANAGE')) {
            this.$Message.warning({
              content: str
              // duration: 0,
              // closable: true
            });
          }
        }
      });
    }
    let self = this;
    Promise.all([
      getDict({ code: 'AG_OUT' }),
      getDict({ code: 'AG_IN' }),
      getDict({ code: 'CBDW' }),
      api.getGameById(self.model.eventsId) // 获取赛事详情
    ])
      .then(data => {
        self.AGOUTS = data[0];
        self.AGINS = data[1];
        self.units = data[2];
        self.detail = {
          eventsId: data[3].eventsId,
          eventsName: data[3].eventsName,
          eventsEnglishName: data[3].eventsEnglishName,
          kindCode: data[3].kindCode,
          gradeCode: data[3].gradeCode,
          startTime: self.$moment(data[3].startTime).valueOf(),
          endTime: self.$moment(data[3].endTime).valueOf(),
          planField: data[3].planField,
          competitionState: data[3].competitionState
        };
        self.modelTemp.kindCode = data[3].kindCode;
        self.modelTemp.gradeCode = data[3].gradeCode;
        self.modelTemp.operatingCompany = data[3].undertakingUnit;
        self.initing = true;
        self.fetchListStart();
      })
      .catch(err => {
        self.initing = true;
        self.fetchListStart();
      });

    // }
  },
  methods: {
    back() {
      let path = '/game-management/';
      let { kindCode } = this.detail;
      switch (kindCode) {
        case '-1':
          path += 'amateur';
          break;
        case '0':
          path += 'teen';
          break;
        case '1':
          path += 'career-man';
          break;
        case '2':
          path += 'women/career-women';
          break;
        case '20':
          path += 'women/women-two';
          break;
        case '3':
          path += 'history/amateur/man';
          break;
        case '4':
          path += 'history/amateur/women';
          break;
        case '5':
          path += 'history/teen/man-a';
          break;
        case '6':
          path += 'history/teen/women-a';
          break;
        case '7':
          path += 'history/teen/man-b';
          break;
        case '8':
          path += 'history/teen/women-b';
          break;
        default:
          path += 'career-man';
          break;
      }
      this.$router.push({ path });
    },
    getCode(obj) {
      let self = this;
      if (obj.code === 'AG_OUT') {
        if (obj.val !== 'A156') {
          self.model.fieldAddressProvince = null;
          self.model.fieldAddressCounty = null;
          self.model.fieldAddressCity = null;
        }
      }
      self.$forceUpdate();
    },
    getData(obj) {
      let self = this;
      if (obj.code === 'CBDW') {
        obj.units = obj.data;
      }
    },
    getVal(expression) {
      let self = this;
      eval(expression);
    },
    // 获取数据
    fetchListStart() {
      let self = this;
      self.page = { ...self.page, ...self.pageModel, pageNo: 1 };
      self.selectedTableItems = [];
      self.fetchList();
    },
    fetchList() {
      this.loading = true;
      api
        .querymatchList(this.page)
        .then(data => {
          this.loading = false;
          this.tableData = data.list || [];
          this.total = data.count || 0;
        })
        .catch(error => {
          this.loading = false;
        });
    },
    // 分页
    changePage(pageNum) {
      this.page.pageNo = pageNum;
      this.fetchList();
    },
    // 重置
    reset() {
      let self = this;
      Object.keys(self.pageModel).forEach(x => {
        self.pageModel[x] = null;
      });
      this.fetchListStart();
    },
    // 保存
    save() {
      let self = this;
      this.$refs['model'].validate(valid => {
        if (valid) {
          self.saving = true;
          let model = { ...self.model };
          if (self.access.includes('GAME_MANAGER')) {
            model.eventApplyId = self.checkObj.eventApplyId;
            model.applyId = self.checkObj.applyId;
            if (model.operationType == null) {
              model.operationType = '1';
            } else if (model.operationType === '4') {
              model.operationType = '2';
            }
            apiApply.editMatch(model).then(data => {
              self.saving = false;
              if (data) {
                self.$router.push(`/game-apply-management/match/${data}`);
              }
            });
          } else {
            model = _.omit({ ...model }, [
              "userNum"
            ]);
            api
              .matchadd(model)
              .then(data => {
                self.saving = false;
                if (data) {
                  self.cancel();
                  self.fetchList();
                }
              })
              .catch(error => {
                self.saving = false;
              });
          }
        }
      });
    },
    // 删除
    del(fieldId) {
      let self = this;
      if (self.access.includes('GAME_MANAGER')) {
        apiApply
          .editMatch({
            fieldId,
            eventsId: self.model.eventsId,
            operationType: 3
          })
          .then(data => {
            if (data) {
              self.$router.push(`/game-apply-management/match/${data}`);
            }
          });
      } else {
        api.matchdel(fieldId).then(data => {
          if (data) {
            this.fetchListStart();
          }
        });
      }
    },
    delMore() {
      let self = this;
      if (self.selectedTableItems.length === 0) {
        self.$Message.warning('请至少选择一条');
        return;
      }
      let params = { fieldIdList: [] };
      params.fieldIdList = self.selectedTableItems.map(item => {
        return parseInt(item.fieldId);
      });
      self.loading = true;
      api.batchDelete(params).then(data => {
        if (data) {
          this.fetchListStart();
        }
      });
    },
    // 全选
    isSelected(_selected) {
      this.selectedTableItems = _selected;
    },
    // 发布 取消发布
    public(id, num) {
      let params = {
        fieldIdList: [],
        state: num
      };
      let self = this;
      if (!id) {
        if (this.selectedTableItems.length === 0) {
          this.$Message.warning('请至少选择一条');
          return;
        }
        params.fieldIdList = this.selectedTableItems.map(item => {
          return parseInt(item.fieldId);
        });
      } else {
        params.fieldIdList = [id];
      }

      api
        .matchpublic(params)
        .then(data => {
          self.loading = false;
          self.fetchListStart();
        })
        .catch(error => {
          self.selectedTableItems = [];
          self.loading = false;
        });
    },
    // 退出
    cancel() {
      let self = this;
      self.$refs['model'].resetFields();
      this.visible = false;
      this.loading = false;
    },
    see() {
      if(this.detail.kindCode === '-1' || this.detail.kindCode === '0') {
        this.$router.push({
        path:
          '/game-management/edit-other' +
          '/' +
          this.detail.kindCode +
          '/' +
          this.detail.eventsId
      });
      } else {
        this.$router.push({
          path:
            '/game-management/edit' +
            '/' +
            this.detail.kindCode +
            '/' +
            this.detail.eventsId
        });
      }
    },
    //点击弹窗
    dialog(item) {
      let self = this;
      if (item) {
        self.model = { ...item };
        Object.defineProperties(self.model, {
          _index: { enumerable: false },
          _rowKey: { enumerable: false }
        });
        self.model.fieldTime = self.model.fieldTime && self.$moment(self.model.fieldTime).toDate();
        self.model.fieldEndTime =
          self.model.fieldEndTime != null
            ? self.$moment(self.model.fieldEndTime).toDate()
            : null;
      } else {
        if (
          self.detail.planField == null ||
          self.detail.planField > self.total
        ) {
          self.model = { ...self.modelTemp };
          self.model.fieldNumber = self.total + 1;
        } else {
          this.$Message.warning(
            `${self.detail.eventsName} 赛事设置计划场次为${
              self.detail.planField
            }场，已全部创建`
          );
          return;
        }
      }
      self.visible = true;
    },
    // 导出excel
    exportExcel() {
      let self = this;
      let params = self.page;
      api.ExportFieldExcel(params).then(fileUrl => {
        let link = document.createElement('a');
        link.href = fileUrl;
        let suffix = fileUrl.substr(fileUrl.lastIndexOf('.'));
        link.download = self.detail.eventsName + '场次安排' + suffix;
        link.click();
      });
    },
    // 批量导入
    importExcel(fileUrl) {
      let self = this;
      let params = {
        ftpFile: fileUrl,
        eventsId: self.detail.eventsId
      };
      api.importFieldExcel(params).then(data => {
        self.fetchListStart();
      });
    },
    downloadExcel() {
      let link = document.createElement('a');
      link.href = this.$config.fieldExcelTempUrl;
      link.download = '比赛场次批量导入模板.xlsx';
      link.click();
    }
  }
};
</script>

<style scoped>
.ivu-btn-primary {
  margin: 0 4px;
}
.ivu-card-bordered {
  border: 1px solid #fff;
}
.ivu-card:hover {
  box-shadow: none;
}
.demo-spin-col {
  border: none;
}
.ivu-input-number {
  width: 100%;
}
.detail .ivu-btn:focus {
  box-shadow: none;
}
</style>
